#include <sys/types.h> 
#include <sys/stat.h> 
#include <string.h> 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> 
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <assert.h>
#include <time.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <linux/types.h>
#include "cetc14-iic.h"

int higher2lower(char c);
int htoi(char s[]);

#define CREAT_MASK(start,end) (~(0xffffffff << (start - end + 1)) << end)



int main(int argc, char *argv[]) 
{
	unsigned int index,baseadd,flag;
	unsigned int delay,bank,cfg;
	unsigned int reg_address,value;
	unsigned int i = 0;
	unsigned int tempval,addr[3] = {0};
	unsigned int sdi_index;

	baseadd = 0;
	bank = htoi(argv[1]);
	value = htoi(argv[2]);
	flag = htoi(argv[3]);
	sdi_index=htoi(argv[4]);

	addr[0] = 0x308000 + 0x20000 * bank + 0x5044;
	addr[1] = 0x308000 + 0x20000 * bank + 0x504C;
	addr[2] = 0x308000 + 0x20000 * bank + 0x5040;

	for(i = 0;i < 512;i++)
	{
		if(flag == 0)
		{
			printf("================write==============\n");
			tempval = i << 4 | 0x0;
			printf("WRITE:Address = 0x%08x, value = 0x%x\n",addr[0],tempval);
			iic_access(sdi_index,0x58,addr[0],&tempval,0);

			tempval = value;
			printf("WRITE:Address = 0x%08x, value = 0x%x\n",addr[1],tempval);
			iic_access(sdi_index,0x58,addr[1],&tempval,0);

			tempval = 1;
			printf("WRITE:Address = 0x%08x, value = 0x%x\n",addr[2],tempval);
			iic_access(sdi_index,0x58,addr[2],&tempval,0);
		}
		else
		{
			printf("================read==============\n");
			tempval = i << 4 | 0x0 | 0x80000000;
			printf("WRITE:Address = 0x%08x, value = 0x%x\n",addr[0],tempval);
			iic_access(sdi_index,0x58,addr[0],&tempval,0);

			tempval = 1;
			printf("WRITE:Address = 0x%08x, value = 0x%x\n",addr[2],tempval);
			iic_access(sdi_index,0x58,addr[2],&tempval,0);

			iic_access(sdi_index,0x58,addr[1],&tempval,1);
			printf("READ :Address = 0x%08x, value = 0x%x\n",addr[1],tempval);
			if(tempval != value)
			{
				printf("ERROR:read value error,0x%x != 0x%x\n",value,tempval);
			}
		}
	}
	return 0;
}
																	
int higher2lower(char c)
{
	if(c >= 'A' && c <= 'Z')
		return c + 'a' - 'A';
	else
	  return c;
}

int htoi(char s[])
{
	int i;
	int n = 0;
	if(s[0] == '0' && (s[1] == 'x' || s[1] == 'x'))
	  i = 2;
	else
	  i = 0;
	for(;(s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f') \
			|| (s[i] >= 'A' && s[i] <= 'F'); ++i)
	{
		if(higher2lower(s[i] > '9'))
		{
			n = 16 * n +(10 + higher2lower(s[i]) - 'a');
		}
		else
		  n = 16 * n + (higher2lower(s[i] - '0'));
	}
	return n;
}
